using AppToolKit.Business.Observer;
using AppToolKit.Data;
using AppToolKit.Data.NHibernate;
using AppToolKit.Model;
using AppToolKit.Model.Validation;
using Common.Logging;
using Spring.Transaction.Interceptor;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace AppToolKit.Business
{
	public abstract class BusinessBase<T> : ISubject, IBusiness<T> where T : class, IEntity
	{
		private static readonly ILog logger_ = LogManager.GetLogger(typeof(IBusiness<T>));
		private IObserverManager manager_;
		private bool isFactoryRegister_ = false;
		protected IEntityFactory<T> factory_;
		protected IDataAccessObject<T> dao_;
		private EntityMeta entityMeta_;
		private BusinessSupport suppor_;
		public IObserverManager ObserveMgr
		{
			get
			{
				return this.manager_;
			}
			set
			{
				this.manager_ = value;
			}
		}
		public virtual IDataAccessObject<T> Dao
		{
			get
			{
				if (null == this.dao_)
				{
					Debug.Assert(null != this.suppor_);
					this.dao_ = this.suppor_.DaoFactory.Create<T>();
				}
				return this.dao_;
			}
			set
			{
				this.dao_ = value;
				Debug.Assert(this.dao_ != null);
			}
		}
		public BusinessSupport Support
		{
			get
			{
				return this.suppor_;
			}
			set
			{
				this.suppor_ = value;
				Debug.Assert(this.suppor_ != null);
				if (this.suppor_ != null)
				{
					this.entityMeta_ = this.suppor_.MetaCenter.GetMeta(typeof(T));
					BusinessBase<T>.logger_.Debug(string.Format("注册{0}类型内置的验证器", typeof(T)));
					this.suppor_.ValidationFactory.CollectValidator(typeof(T));
					if (this.factory_ != null && !this.isFactoryRegister_)
					{
						if (this.suppor_.ValidationFactory.TryRegisted(typeof(T), this.factory_.GetType()))
						{
							BusinessBase<T>.logger_.Debug(string.Format("注册{0}类型工厂提供的验证器", typeof(T)));
							this.factory_.RegisterValidator();
							this.isFactoryRegister_ = true;
						}
					}
				}
			}
		}
		public IEntityFactory<T> Factory
		{
			get
			{
				return this.factory_;
			}
			set
			{
				this.factory_ = value;
				if (this.factory_ != null)
				{
					this.factory_.Business = this;
					if (this.suppor_ != null && !this.isFactoryRegister_)
					{
						if (this.suppor_.ValidationFactory.TryRegisted(typeof(T), this.factory_.GetType()))
						{
							this.factory_.RegisterValidator();
							this.isFactoryRegister_ = true;
						}
					}
				}
			}
		}
		private EntityMeta entityMeta
		{
			get
			{
				if (this.entityMeta_ == null)
				{
					this.entityMeta_ = this.suppor_.MetaCenter.GetMeta(typeof(T));
				}
				return this.entityMeta_;
			}
		}
		public BusinessBase()
		{
		}
		[Transaction(ReadOnly = false, NoRollbackFor = new Type[]
		{
			typeof(NoRollbackException)
		})]
		public void Save(T entity, Opeartion op)
		{
			this.SaveEntity(entity, op);
			ObserveEventCallbackArgs observeEventCallbackArgs = new ObserveEventCallbackArgs();
			observeEventCallbackArgs.Current = entity;
			observeEventCallbackArgs.Opeartion = op;
			this.PublishEvent(typeof(T).FullName, "SUBSCIBEEVENT_SAVE", observeEventCallbackArgs);
		}
		private void SaveEntity(T entity, Opeartion op)
		{
			if (this.factory_ != null)
			{
				this.factory_.BeforeSave(entity);
			}
			this.ValidateAndThrow(entity, ValidateBehavior.Save);
			this.DoSave(entity);
			if (this.factory_ != null)
			{
				this.factory_.AfterSave(entity);
			}
		}
		[Transaction(ReadOnly = false, NoRollbackFor = new Type[]
		{
			typeof(NoRollbackException)
		})]
		public void SaveWithoutPublish(T entity, Opeartion op)
		{
			this.SaveEntity(entity, op);
		}
		private void DoSave(T entity)
		{
			try
			{
				BusinessBase<T>.logger_.Debug(string.Format("保存{0},key:{1}", entity.GetType(), entity.Key));
				this.dao_.Save(entity);
			}
			catch (Exception ex)
			{
				BusinessBase<T>.logger_.Error(string.Format("保存失败({0}),原因{1}", base.GetType(), ex.Message));
				if (!(ex is NoRollbackException))
				{
					throw;
				}
			}
		}
		private void ValidateAndThrow(T entity, ValidateBehavior behavior)
		{
			ValidateResultSet validateResultSet = this.ValidateFlow(entity, behavior);
			if (!validateResultSet.IsValid)
			{
				throw new ValidateException
				{
					ResultSet = validateResultSet
				};
			}
			this.ValidateChain(entity, behavior);
		}
		protected virtual void ValidateChain(T entity, ValidateBehavior behavior)
		{
		}
		private ValidateResultSet ValidateFlow(object entity, ValidateBehavior behavior)
		{
			ValidateResultSet validateResultSet = this.Support.ValidationFactory.Validate(typeof(T), entity, behavior);
			ValidateResultSet result;
			if (!validateResultSet.IsValid)
			{
				result = validateResultSet;
			}
			else
			{
				if (this.factory_ != null)
				{
					validateResultSet = this.factory_.Valid(entity, ValidateBehavior.Save);
					if (!validateResultSet.IsValid)
					{
						result = validateResultSet;
						return result;
					}
				}
				result = new ValidateResultSet();
			}
			return result;
		}
		[NoRollbackRule(typeof(NoRollbackException))]
		public void Delete(T entity, Opeartion op)
		{
			if (this.factory_ != null)
			{
				this.factory_.BeforeDelete(entity);
			}
			this.DoDelete(entity);
			if (this.factory_ != null)
			{
				this.factory_.AfterDelete(entity);
			}
			ObserveEventCallbackArgs observeEventCallbackArgs = new ObserveEventCallbackArgs();
			observeEventCallbackArgs.Current = entity;
			observeEventCallbackArgs.Opeartion = op;
			this.PublishEvent(typeof(T).FullName, "SUBSCIBEEVENT_DELETE", observeEventCallbackArgs);
		}
		private void DoDelete(T entity)
		{
			try
			{
				this.dao_.Delete(entity);
			}
			catch (Exception ex)
			{
				if (!(ex is NoRollbackException))
				{
					throw;
				}
			}
		}
		[Transaction(ReadOnly = false, NoRollbackFor = new Type[]
		{
			typeof(NoRollbackException)
		})]
		public void Update(T entity, Opeartion op)
		{
			T t = Activator.CreateInstance<T>();
			this.dao_.Load(t, entity.Key);
			this.UpdateEntity(entity, op);
			ObserveEventCallbackArgs observeEventCallbackArgs = new ObserveEventCallbackArgs();
			observeEventCallbackArgs.Current = entity;
			observeEventCallbackArgs.Old = t;
			observeEventCallbackArgs.Opeartion = op;
			this.PublishEvent(typeof(T).FullName, "SUBSCIBEEVENT_UPDATE", observeEventCallbackArgs);
		}
		[Transaction(ReadOnly = false, NoRollbackFor = new Type[]
		{
			typeof(NoRollbackException)
		})]
		public void UpdateWithoutPublish(T entity, Opeartion op)
		{
			this.UpdateEntity(entity, op);
		}
		private void UpdateEntity(T entity, Opeartion op)
		{
			if (this.factory_ != null)
			{
				this.factory_.BeforeUpdate(entity);
			}
			this.ValidateAndThrow(entity, ValidateBehavior.Update);
			this.DoUpdate(entity);
			if (this.factory_ != null)
			{
				this.factory_.AfterUpdate(entity);
			}
		}
		private void DoUpdate(T entity)
		{
			try
			{
				BusinessBase<T>.logger_.Debug(string.Format("更新{0},key:{1}", entity.GetType(), entity.Key));
				this.dao_.Update(entity);
				BusinessBase<T>.logger_.Debug(string.Format("更新完毕,{0}", typeof(T)));
			}
			catch (Exception ex)
			{
				BusinessBase<T>.logger_.Error(string.Format("更新失败({0}),原因{1}", base.GetType(), ex.Message));
				if (!(ex is NoRollbackException))
				{
					throw;
				}
			}
		}
		public virtual T Create()
		{
			T t = Activator.CreateInstance<T>();
			if (this.factory_ != null)
			{
				this.factory_.AfterCreate(t);
			}
			return t;
		}
		public IList<T> GetAll()
		{
			return this.dao_.GetAll();
		}
		public void Delete(string queryString)
		{
			this.dao_.Delete(queryString);
		}
		public ValidateResultSet Valid(T entity, ValidateBehavior behavior)
		{
			return this.ValidateFlow(entity, behavior);
		}
		public ValidateResultSet Valid(string property, object entity, object value, ValidateBehavior behavior)
		{
			ValidatorCollection fieldValidators = this.suppor_.ValidationFactory.ValidateLib[typeof(T).FullName].GetFieldValidators(property, behavior);
			ValidateResultSet result;
			if (fieldValidators != null)
			{
				result = fieldValidators.Validate(entity, value);
			}
			else
			{
				result = new ValidateResultSet();
			}
			return result;
		}
		public IList<T> GetList(string query)
		{
			return this.dao_.GetList(query);
		}
		public IList<T> GetList(string query, params object[] args)
		{
			HSqlQuery right = HSqlQuery.Format(query, args);
			return this.dao_.GetList(right);
		}
		public void Refresh(T entity)
		{
			this.dao_.Refresh(entity);
		}
		public T Load(object t)
		{
			T result;
			if (t == null)
			{
				result = default(T);
			}
			else
			{
				T t2 = this.dao_.Load(t);
				if (this.factory_ != null)
				{
					this.factory_.AfterLoad(t2);
				}
				result = t2;
			}
			return result;
		}
		public IList<T> GetListByPage(string query, int start, int Max)
		{
			return this.dao_.GetListByPage(query, start, Max);
		}
		public void Load(ref T data, object key)
		{
			if (key == null)
			{
				data = default(T);
			}
			else
			{
				this.dao_.Load(data, key);
				if (this.factory_ != null)
				{
					this.factory_.AfterLoad(data);
				}
			}
		}
		protected void PublishEvent(string subject, string eventName, ObserveEventCallbackArgs args)
		{
			if (this.manager_ != null)
			{
				this.manager_.PublishEvent(this, subject, eventName, args);
			}
		}
	}
}
